package com.heima.kafka.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
public class KafkaStreamHelloHandler {

    @Bean
    public KStream<String,String> kStream(StreamsBuilder streamsBuilder){
        //从哪个topic中接收消息,创建stream对象
        KStream<String, String> stream = streamsBuilder.stream("stream-input-topic");

        //流式处理
        /**
         * 把消息的内容切割之后，把一个一个的单词装入到集合中
         * hello kafka
         */
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        String[] split = value.split(" ");
                        return Arrays.asList(split);

                    }
                })
                //按照单词聚合
                .groupBy((key,value)->value)
                //时间窗口,每5秒聚合一次
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //计算单词的个数，消息的key和value会发生变化：key:单词，value:个数（long）
                .count()
                .toStream()
                //把消息的类型转换
                .map((key,value)->{

                    return new KeyValue<>(key.key().toString(),value.toString());
                }).to("stream-out-topic");

        return  stream;
    }
}
